package com.test.springboot.mybatis.conf;

import com.alibaba.druid.pool.DruidDataSourceFactory;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;
import java.util.Properties;

/**
 * @author chenxubing
 */
@org.springframework.context.annotation.Configuration
@MapperScan({"com.test.springboot.mybatis.dao.mapper"})
public class SqlSessionConfig {
    @Bean
    @ConfigurationProperties(prefix = "spring.datasource")
    public DataSource dataSource(Properties dataSource) throws Exception {
        return DruidDataSourceFactory.createDataSource(dataSource);
    }

    @Bean
    @ConfigurationProperties(prefix = "spring.mybatis.configuration")
    public Configuration mybatisConfiguration() {
        return new Configuration();
    }

    @Bean
    @Primary
    public SqlSessionFactory sqlSessionFactory(Configuration mybatisConfiguration, DataSource dataSource) throws Exception {
        final SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setConfiguration(mybatisConfiguration);
        sqlSessionFactoryBean.setDataSource(dataSource);
        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        sqlSessionFactoryBean.setMapperLocations(resolver.getResources("classpath:/mybatis/**/*Mapper.xml"));
        return sqlSessionFactoryBean.getObject();
    }
}